2190

11 分钟

#assert.h

这个头文件提供 编译时断言 的相关功能,用于开发和调试阶段验证程序的假设条件是否成立。

如果 assert 宏的断言不成立,则在 stderr 上输出诊断信息并调用 abort 中止程序。

在 Release 版本中,可以通过定义 NDEBUG 宏,可以屏蔽断言,从而消除运行时开销。

示例:

#include <stdio.h> // #define NDEBUG // 在引入 assert.h 之前定义 NDEBUG 可以屏蔽 assert #include <assert.h> #include <math.h> int main(void) { double x = -1.0; assert(x > 0.0); // 断言 x 大于 0,因为对数函数的定义域为 x > 0 printf("log(x) = %f\n", log(x)); return 0; }

运行结果:

user@host:~ $ gcc main.c -lm
user@host:~ $ ./a.out
a.out: main.c:10: main: Assertion `x > 0.0' failed.
Aborted (core dumped)

在该示例中,我们要计算 x 的对数,而对数函数的定义域为 x > 0,因此通过 assert 断言 x > 0

在开发调试阶段,如果发现存在 x <= 0 的情况,assert 会输出诊断信息并调用 abort 中止程序,便于快速发现问题。

在保障 x <= 0 的情况不会再出现后,发布阶段通过定义 NDEBUG 宏屏蔽 assert 以降低开销提升程序性能。

如果无法保障 x > 0,则应当通过条件语句进行错误处理以提高程序的健壮性。

#

说明
assert如果用户指定的条件不成立,则中止程序。在 Release 版本中可能会被屏蔽。

#示例

#include <stdio.h> // #define NDEBUG // 在引入 assert.h 之前定义 NDEBUG 可以屏蔽 assert #include <assert.h> #include <math.h> int main(void) { double x = -1.0; assert(x > 0.0); // 断言 x 大于 0,因为对数函数的定义域为 x > 0 printf("log(x) = %f\n", log(x)); return 0; }

运行结果:

user@host:~ $ gcc main.c -lm
user@host:~ $ ./a.out
a.out: main.c:10: main: Assertion `x > 0.0' failed.
Aborted (core dumped)

在该示例中,我们要计算 x 的对数,而对数函数的定义域为 x > 0,因此通过 assert 断言 x > 0

在开发调试阶段,如果发现存在 x <= 0 的情况,assert 会输出诊断信息并调用 abort 中止程序,便于快速发现问题。

在保障 x <= 0 的情况不会再出现后,发布阶段通过定义 NDEBUG 宏屏蔽 assert 以降低开销提升程序性能。

创建于 2025/6/1

更新于 2025/6/6